home *** CD-ROM | disk | FTP | other *** search
- Path: crl.crl.com!not-for-mail
- From: bobfry@crl.com (Robert Fry)
- Newsgroups: comp.lang.c
- Subject: Re: Character String --> Integer
- Date: 8 Feb 1996 10:49:40 -0800
- Organization: CRL Dialup Internet Access
- Message-ID: <4fdgk4$m2@crl.crl.com>
- References: <4fb0ga$lsa@remus.rutgers.edu>
- NNTP-Posting-Host: crl.com
-
- wempa@remus.rutgers.edu (Force Of Nature) writes:
-
- >Is there an easy way to convert a character string such as '2425' to the
- >integer 2425 ??? The only way I can think of is to pick off characters
- >one at a time and use switch statements to determine the value (0-9) and
- >then multiply by the correct power of 10. Is there an easier way to do
- >this ???????
-
- This question should really be in the FAQ since it's a rather common one.
- But I can think of three methods that are used fairly often:
-
- sscanf()
- atoi()
- for(result=0,ptr=string;*ptr;*ptr++)result=10*result+*ptr-'0';
-
- (Note that the last hasn't been checked and doesn't handle errors (such
- as overflow or non-digits) and no doubt has several other problems with
- it -- but should illustrate a more compact method than switch().)
- Bob
-